interface ICacheObj {
  data: any;
  timer: number;
}

class CacheManger {
  private cache: Map<string, ICacheObj>;
  timeout: number;
  constructor(timeout: number) {
    this.cache = new Map();
    this.timeout = timeout;
  }
  generateKey(url: string, ps: any) {
    return url + "?" + Object.keys(ps).map(v => `${v}=${ps[v]}`).join("&");
  }

  setCache(url: string, ps: any, data: any, timeout: number) {
    const cacheKey: string = this.generateKey(url, ps);
    // 如果已经缓存了，清除掉重新缓存
    if (this.cache.has(cacheKey)) {
      clearTimeout(this.cache.get(cacheKey)!.timer);
      console.log(`清除${cacheKey}缓存计时器`);
    }
    // 清除缓存
    this.cache.delete(cacheKey);

    // 设置新的缓存
    const cacheObj = {
      data: data,
      // 设置缓存有效时长
      timer: setTimeout(() => {
        this.cache.delete(cacheKey);
        console.log(`缓存${cacheKey}失效自动清除`);
      }, timeout)
    };
    console.log(cacheObj);
    this.cache.set(cacheKey, cacheObj);
  }

  getCache(url: string, ps: any): ICacheObj | undefined {
    // 获得缓存key
    const cacheKey: string = this.generateKey(url, ps);
    // 如果缓存存在，直接取
    const currCache = this.cache.get(cacheKey);
    const res = !!currCache ? currCache?.data : undefined;
    console.log("获取到的缓存：", res);
    return res;
  }
}

const c = new CacheManger(5000);

const url = 'http://xxxx.com';
const url1 = 'http://xxxx.com/1';
const ps = {
  a: 1,
  b: 2,
  c: 3
};

const cacheKey = c.generateKey(url, ps);
console.log(cacheKey);
c.setCache(url, ps, "我是数据嘿嘿嘿", 5000);
c.setCache(url1, ps, "我是数据1嘿嘿嘿", 5000);

setTimeout(() => {
  c.getCache(url1, ps,);
}, 2000);

// yeah 写完了
